package com.xhsj.user.pms.oareply.service;

import com.xhsj.user.generalprocess.service.TbPamGeneralProcessTaskService;
import com.xhsj.user.generalprocess.vo.GeneralAuditVo;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.pms.oareply.dto.*;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOaCorrection;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOaCorrectionFile;
import com.xhsj.user.pms.oareply.mapper.TbPamPatentOaCorrectionFileMapper;
import com.xhsj.user.pms.oareply.mapper.TbPamPatentOaCorrectionMapper;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.pms.oareply.vo.CorrectionFileListVo;
import com.xhsj.user.pms.oareply.vo.FindToAuditVo;
import com.xhsj.user.pms.oareply.vo.ProcessTableNameVo;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.utils.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 专利OA补正 服务实现类
 * </p>
 *
 * @author liuqinghua
 * @since Jul 28, 2021 8:03:42 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TbPamPatentOaCorrectionService extends BaseService<TbPamPatentOaCorrectionMapper, TbPamPatentOaCorrection> {
    @Autowired
    private TbPamPatentOaCorrectionMapper dao;

    @Autowired
    private TbPamGeneralProcessTaskService tbPamGeneralProcessTaskService;

    @Autowired
    private TbPamPatentOaCorrectionFileService tbPamPatentOaCorrectionFileService;

    @Autowired
    private TbPamPatentOaCorrectionFileMapper tbPamPatentOaCorrectionFileMapper;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;

    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;

    //角色名称 知产部负责人
    @Value("${rolekeyname.zszl1}")
    private String zszl1;

    /**
     * 保存
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:03:42 AM
     */
    @Override
    public boolean save(TbPamPatentOaCorrection entity) {
        return super.save(entity);
    }

    /**
     * 通过id获取数据
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:03:42 AM
     */
    @Override
    public TbPamPatentOaCorrection getById(Serializable id) {
        return super.getById(id);
    }

    /**
     * 通过id删除数据
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:03:42 AM
     */
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    /**
     * 分页查询数据
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:03:42 AM
     */
    public IPage<TbPamPatentOaCorrection> selectPage(Map<String, Object> data) {
        int currentPage = 1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage = (Integer) data.get("page");
        }
        int pageSize = 20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize = (Integer) data.get("size");
        }

        TbPamPatentOaCorrection entity = JSON.parseObject(JSON.toJSONString(data), TbPamPatentOaCorrection.class);
        Page<TbPamPatentOaCorrection> page = new Page(currentPage, pageSize);
        QueryWrapper<TbPamPatentOaCorrection> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

    /**
     * 查询所有数据
     *
     * @author liuqinghua
     * @date Jul 28, 2021 8:03:42 AM
     */
    @Override
    public List<TbPamPatentOaCorrection> selectAll() {
        return super.selectAll();
    }


    /**
     * @Description: 专利OA补正流程启动
     * @Param:
     * @return:
     * @Author: liuqinghua
     * @Date: 2021/7/28
     */
    public void startOACorrectionProcess(StartOACorrectionProcessDto param) throws Exception {
        // 保存申请表
        TbPamPatentOaCorrection tbPamPatentOaCorrection = new TbPamPatentOaCorrection();
        BeanUtils.copyProperties(param, tbPamPatentOaCorrection);
        if (!super.save(tbPamPatentOaCorrection))
            throw new Exception("OA答复模块-OA补正保存申请表错误");
        // 执行流程
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        BeanUtils.copyProperties(param, generalAuditVo);
        generalAuditVo.setDataId(tbPamPatentOaCorrection.getId());
        this.setProcessTable(generalAuditVo);
        // 审批人
        generalAuditVo.setUserIds(Arrays.asList(param.getIpr()));
        tbPamGeneralProcessTaskService.startProcess(generalAuditVo, generalCallableVo -> {
            tbPamPatentOaCorrection.setNodeId(generalCallableVo.getNodeId());
            tbPamPatentOaCorrection.setNodeName(generalCallableVo.getNodeName());
            // 修改申请表
            super.updateById(tbPamPatentOaCorrection);
        });
        // 保存文件
        this.saveFiles(param.getFiles(), tbPamPatentOaCorrection.getId());
    }

    public void setProcessTable(GeneralAuditVo generalAuditVo) {
        ProcessTableNameVo vo = new ProcessTableNameVo();
        BeanUtils.copyProperties(vo, generalAuditVo);
        generalAuditVo.setProcessType("patent_bz");
    }

    /**
     * @Description: 专利OA补正-IPR/操作人补正文件流程
     * @Param:
     * @return:
     * @Author: liuqinghua
     * @Date: 2021/7/29
     */
    public void iprCorrectionFileProcess(IprCorrectionFileProcessDto param) throws Exception {
        // 执行流程-知产部负责人
        // 根据角色名查找角色
        List<Long> roleIds = tbGlobalUserService.checkRole(zszl1, "知产部负责人");
        // 检查角色下是否有用户
        tbGlobalUserService.checkRoleUserId(zszl1, "知产部负责人");
        param.setRoleIds(roleIds);
        // 执行流程
        this.handleProcess(param,param.getIpr());
        // 保存文件
        List<TbPamPatentOaCorrectionFile> files = param.getFiles();
        this.saveFiles(files, param.getDataId());

    }

    // 流程
    public void handleProcess(Object param,Long ipr) throws Exception {
        TbPamPatentOaCorrection tbPamPatentOaCorrection = new TbPamPatentOaCorrection();
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        BeanUtils.copyProperties(param, generalAuditVo);
        this.setProcessTable(generalAuditVo);
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
            tbPamPatentOaCorrection.setNodeId(generalCallableVo.getNodeId());
            tbPamPatentOaCorrection.setNodeName(generalCallableVo.getNodeName());
            // 修改申请表
            tbPamPatentOaCorrection.setIpr(ipr);
            tbPamPatentOaCorrection.setId(generalAuditVo.getDataId());
            if (!super.updateById(tbPamPatentOaCorrection))
                throw new Exception("OA答复模块-OA补正修改申请表错误");
        });
    }

    // 保存文件
    public void saveFiles(List<TbPamPatentOaCorrectionFile> files, Long dataId) throws Exception {
        if (files.size() > 0) {
            // 删除
            tbPamPatentOaCorrectionFileService.deleteByDataId(dataId);
            // 新增
            for (TbPamPatentOaCorrectionFile file : files) {
                file.setId(null);
                file.setPatentCorrectionId(dataId);
                file.setCreateDate(file.getCreateDate()==null?new Date():file.getCreateDate());
                file.setUpdateDate(file.getUpdateDate()==null?new Date():file.getUpdateDate());
                file.setCreateBy(file.getCreateBy()==null?UserUtils.getLoginAppUser().getUserId():file.getCreateBy());
                file.setUpdateBy(file.getUpdateBy()==null?UserUtils.getLoginAppUser().getUserId():file.getUpdateBy());
                if (tbPamPatentOaCorrectionFileMapper.insert(file) != 1)
                    throw new Exception("OA答复模块-OA补正保存文件错误");
            }

        }
    }

    /**
     * @Description: 专利OA补正-知产部负责人流程
     * @Author: liuqinghua
     * @Date: 2021/7/29
     */
    public void zszl1Process(Zszl1ProcessDto param) throws Exception {
        if (param.getStatus() == 1) {
            // 审批人
            param.setUserIds(Arrays.asList(param.getIpr()));
        }
        handleProcess(param,param.getIpr());
    }

    /**
     * @Description: 待审核
     * @Author: liuqinghua
     * @Date: 2021/7/29
     */
    public IPage<FindToAuditVo> findToAudit(FindToAuditDto param) {
        Long userId = UserUtils.getLoginAppUser().getUserId();
        // 根据用户名获取角色
        List<Long> roleListByUserId = tbGlobalUserMapper.getRoleIdsByUserId(userId);
        param.setUserId(userId);
        param.setRoleIds(roleListByUserId);
        // 获取待审核列表
        Page<FindToAuditDto> page = new Page(param.getPage(), param.getPageSize());
        return dao.findToAudit(page, param);
    }


    /**
     * @Description: 审核通过
     * @Author: liuqinghua
     * @Date: 2021/7/29
     */
    public IPage<FindToAuditVo> findApproved(FindToAuditDto param) {
        Long userId = UserUtils.getLoginAppUser().getUserId();
        param.setUserId(userId);
        Page<FindToAuditDto> page = new Page(param.getPage(), param.getPageSize());
        return dao.findApproved(page, param);
    }

    /**
     * @Description: 获取补正文件-不分页
     * @Author: liuqinghua
     * @Date: 2021/8/2
     */
    public List<CorrectionFileListVo> findCorrectionFileListNotPage(Long dataId) {
        return tbPamPatentOaCorrectionFileService.findCorrectionFileListNotPage(dataId);
    }

   /**
       * @Description: 我的申请
       * @Author: liuqinghua
       * @Date: 2021/8/9
       */
    public IPage<FindToAuditVo> myApplyList(MyApplyListDto param) {
        Page<FindToAuditVo> page = new Page<>(param.getPage(), param.getPageSize());
        return dao.myApplyList(page, param);
    }
}
